<template>
    <div class="app-container calendar-list-container" v-loading="loading" element-loading-text="正在导出数据">
    <!-- filter 条件查询 -->
    <div class="btn-add">
        <el-button
        icon="el-icon-circle-plus-outline"
        type="button"
        class="el-button el-button--primary"
        @click="addInOrOut"
        >
            新增</el-button
        >
    </div>

    <!-- 新增数据弹窗 -->
    <el-dialog
      :title="title"
      :visible.sync="showAdd"
      @close="closeShow"
      width="65%"
    >
        <el-form :model="createForm" :inline="true" ref="createForm" :rules="addRules">
            <el-row :gutter="0">    
            <el-col :span="6">  
                <el-form-item label="工作中心" prop="workCenter" label-width="90px" >
                <el-select
                    v-model="createForm.workCenter"
                    @focus="getCenterList" 
                    placeholder="请选择工作中心"
                    class="ul-item"
                    filterable
                    clearable>
                    <el-option v-for="(item,index) in this.centerList"  :key="index" :label="item" :value="item"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
                <el-form-item label="内容类别" prop="contentType"  label-width="80px" >
                  <el-select 
                     v-model="createForm.contentType" 
                     clearable      
                     filterable
                     placeholder="请选择培训类别"
                     class="ul-item">
                     <el-option :value="item" :label="item" v-for="(item,index) in this.contentTypeList" :key="index"/>
                </el-select>
                  <!-- <el-input placeholder="请输入内容类别" clearable v-model.trim="createForm.contentType" class="ul-item"/> -->
                </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="培训内容" prop="trainingContent" label-width="80px" >
                <el-input type="textarea" :autosize="{ minRows: 1, maxRows: 4}" placeholder="请输入培训内容" clearable v-model.trim="createForm.trainingContent" class="ul-item" style="width: 340px;"/>  
              </el-form-item>
            </el-col>   
           </el-row>
           <el-row :gutter="0">    
            <el-col :span="6">
              <el-form-item label="导师/讲师" prop="userName"  label-width="90px" >
                <el-select 
                     v-model="createForm.userName" 
                     clearable      
                     filterable
                     @focus="getTutor"
                     @change="changeTutor"
                     placeholder="请选择导师/讲师"
                     class="ul-item">   
                     <el-option :value="item.id" :label="item.userName" v-for="(item,index) in this.tutorList" :key="index"/>
                </el-select>
                <!-- <el-input placeholder="请输入姓名" clearable v-model.trim="createForm.userName" class="ul-item"/> -->
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="培训类别" prop="trainingCategory" label-width="80px" >    
                <el-select 
                     v-model="createForm.trainingCategory" 
                     clearable      
                     filterable
                     placeholder="请选择培训类别"
                     class="ul-item">
                     <el-option :value="item" :label="item" v-for="(item,index) in this.typeList" :key="index"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="培训时间" prop="plannedTrainingTime" label-width="80px" >
                <el-popover v-model="cronverify">
                    <cron @change="changeverify($event,1)" @close="cronverify=false" i18n="cn"></cron>
                    <el-input clearable style="width: 150px;margin: 0 3px 0 0px;" slot="reference" @click="cronverify=true" v-model="createForm.plannedTrainingTime" placeholder="请选择培训时间"></el-input>
                </el-popover>
                <el-input clearable style="width: 180px;margin: 0 3px 0 6px;" v-model="plannedTrainingTime1" class="ul-item" disabled placeholder="此处第一次执行时间"/>
              </el-form-item>
            </el-col>   
           </el-row>
           <el-row :gutter="0">    
            <el-col :span="6">
              <el-form-item label="课件类型" prop="certificateType"  label-width="90px" >
                <el-select 
                     v-model="createForm.certificateType" 
                     clearable      
                     filterable
                     placeholder="请选择课件类型"
                     class="ul-item">   
                     <el-option :value="item" :label="item" v-for="(item,index) in this.coursewareList" :key="index"/>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
                <el-form-item label="培训课件" prop="materialForTraining1"  label-width="80px" >
                    <el-upload
                      class="upload-demo"
                      action="http://192.168.3.11:8086/technologyFile"
                      :on-success="handlePdfSuccess"
                      :on-remove = "removePdf"  
                      :on-change= "pdfRemove"
                      :headers="getHttpHeader"
                      :before-upload="beforeFilsUpload"
                      :limit="5"
                      :file-list="fileList">
                      <el-button size="small" type="primary">点击上传</el-button>
                    </el-upload>
                </el-form-item>
            </el-col>
            <el-col :span="6">
                <el-form-item label="考核方式" prop="evaluationMode"  label-width="80px" >
                <el-select 
                     v-model="createForm.evaluationMode" 
                     clearable      
                     filterable
                     placeholder="请选择考核方式"
                     class="ul-item">   
                     <el-option :value="item" :label="item" v-for="(item,index) in this.assessList" :key="index"/>
                </el-select>
              </el-form-item>
            </el-col>   
            <el-col :span="6">
                <el-form-item v-if="createForm.evaluationMode == '笔试'" label="考试资料" prop="examinationMaterials1"  label-width="80px" >
                    <el-upload
                      class="upload-demo"
                      action="http://192.168.3.11:8086/technologyFile"
                      :on-success="handlePdfSuccess1"
                      :on-remove = "removePdf1"  
                      :on-change= "pdfRemove"
                      :headers="getHttpHeader"
                      :before-upload="beforeFilsUpload"
                      :limit="5"
                      :file-list="fileList1">
                      <el-button size="small" type="primary">点击上传</el-button>
                    </el-upload>
                </el-form-item>
            </el-col> 
           </el-row>
           <el-row :gutter="0">    
            <el-col :span="6">
                <el-form-item label="邮件通知" prop="emailNotification" label-width="90px">    
                    {{ '否 ' }}<el-switch  v-model="createForm.emailNotification" active-value="1" inactive-value="0" />{{ ' 是' }}
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="通知时间" prop="notificationTime" label-width="80px" >
                <el-popover v-model="cronverify1">
                    <cron @change="changeverify($event,2)" @close="cronverify1=false" i18n="cn"></cron>
                    <el-input clearable style="width: 150px;margin: 0 3px 0 0px;" slot="reference" @click="cronverify1=true" v-model="createForm.notificationTime" placeholder="请选择培训时间"></el-input>
                </el-popover>
                <el-input clearable style="width: 180px;margin: 0 3px 0 6px;" v-model="notificationTime1" class="ul-item" disabled placeholder="此处第一次执行时间"/>
              </el-form-item>
            </el-col>   
           </el-row>
           <el-form-item label="培训对象" label-width="90px" prop="trainingObjectsStr">
                <div v-for="(items,index1) in trainObjList" :key="index1" style="margin-bottom: 5px;">
                  <el-select filterable @change="objChang($event,index1)" @focus="getKnowledge" v-model="items.jobTitle" placeholder="请选择" style="width:150px">
                    <el-option
                    v-for="(item,index) in trainList"
                    :key="index"
                    :label="item.jobTitle"
                    :value="item.id">
                  </el-option>
                </el-select>
                <el-button style="margin-left: 5px;" type="danger" icon="el-icon-delete" circle @click="delPost(index1)"></el-button>
                <el-button v-if="index1 == 0" style="margin-left: 5px;" type="primary" icon="el-icon-plus" circle @click="addPost"></el-button>
              </div>
            </el-form-item>

           <el-form-item label="邮件抄送" label-width="80px">
                <div v-for="(items,index1) in MailUserName" :key="index1" style="margin-bottom: 5px;">
                  <el-select  @change="mailChang($event,index1)" filterable @focus="businessFocus" v-model="items.name" placeholder="请选择" style="width:150px">
                    <el-option
                    v-for="(item,index) in personnelList"
                    :key="index"
                    :label="item.userName"
                    :value="item.userName">
                  </el-option>
                </el-select>
                <el-button style="margin-left: 5px;" type="danger" icon="el-icon-delete" circle @click="delMail(index1)"></el-button>
                <el-button v-if="index1 == 0" style="margin-left: 5px;" type="primary" icon="el-icon-plus" circle @click="addMail"></el-button>
              </div>
            </el-form-item>
            
        </el-form>

        <!-- 公共底部 -->
        <div slot="footer" class="dialog-footer">
            <el-button @click="showAdd = false">取 消</el-button>
            <el-button
            type="primary"
            @click="addfacility('createForm')"
             :loading="loadBool"
            >确 认</el-button
            >
        </div>
    </el-dialog>


    <div class="filter-container">
      <!-- style="width: 150px;margin-right:15px;" -->

        <el-select 
             v-model="param.workCenter" 
             clearable      
             filterable
             style="margin-right: 15px;width: 150px"
             @focus="getCenterList" 
             placeholder="请选择工作中心"
             class="ul-item">
             <el-option :value="item" :label="item" v-for="(item,index) in this.centerList" :key="index"/>
        </el-select>

        <el-select 
             v-model="param.trainingCategory" 
             clearable      
             filterable
             style="margin-right: 15px;width: 180px"
             placeholder="请选择培训类别"
             class="ul-item">
             <el-option :value="item" :label="item" v-for="(item,index) in this.typeList" :key="index"/>
        </el-select>

        <el-input
            @keyup.enter.native="getData"
            clearable
            style="margin-right: 15px;width: 150px"
            v-model="param.trainingContent"
            placeholder="请输入培训内容"
        ></el-input>

        <el-select 
             v-model="param.tid" 
             clearable      
             filterable
             @focus="getTutor"
             style="margin-right: 15px;width: 140px"
             placeholder="请选择培训导师"
             class="ul-item">
             <el-option :value="item.id" :label="item.userName" v-for="(item,index) in this.tutorList" :key="index"/>
        </el-select>

        <el-button type="primary" v-waves icon="el-icon-search" @click="getData">搜索</el-button>
        <el-button
            type="button"
            v-waves
            class="el-button el-button--warning"
            @click="cancelSubmit"
        >
        重置</el-button>

    </div>

    <!-- table 表格 -->
    <el-table  :data="tableInfo" v-loading="loadingList" element-loading-text="给我一首歌的时间" stripe border fit highlight-current-row style="width: 100%;margin-top:15px;">
      <el-table-column  label="序号" type="index" align="center" width="80px"/>
      <el-table-column label="工作中心"  prop="workCenter" align="center"/>
      <el-table-column label="内容类别"  prop="contentType" align="center"/>
      <el-table-column label="培训内容"  prop="trainingContent" align="center"/>
      <el-table-column label="导师/讲师"  prop="userName" align="center"/>
      <el-table-column label="直接主管"  prop="immediateBoss" align="center"/>
      <el-table-column label="培训类别"  prop="trainingCategory" align="center"/>
      <el-table-column label="计划培训时间"  prop="plannedTrainingTime" align="center"/>
      <el-table-column label="培训对象(岗位)"  prop="trainingObjectsStr" align="center"/>
      <el-table-column label="考核方式"  prop="evaluationMode" align="center" width="200px"/>
      <el-table-column label="课件类型"  prop="certificateType" align="center"/>
      <el-table-column label="邮件通知"  prop="emailNotification" align="center"/>
      <el-table-column label="通知时间"  prop="notificationTime" align="center"/>
      <el-table-column label="抄送人员"  prop="carbonCopyRecipientsUserName" align="center"/>
      <el-table-column label="培训资料/考试资料" align="center" width="200px">
        <template slot-scope="scope" >
            <el-button size="mini" type="primary" @click="clickFor(scope.row)">获取资料</el-button>
        </template>
      </el-table-column>
      <el-table-column label="状态"  prop="type" align="center"/>
      <el-table-column label="完成时间"  prop="completionTime" align="center"/>
      <el-table-column label="培训时长(h)"  prop="longTrainingPeriod" align="center"/>
      <el-table-column label="效果评分"  prop="effectScore" align="center"/>    
      <el-table-column label="评价二维码"  prop="evaluationQrCode" align="center"/>
      <el-table-column label="修改人员"  prop="updateJobNumber" align="center"/>
      <el-table-column label="修改时间"  prop="updateTime" align="center"/> 
      <el-table-column label="操作" fixed="right" align="center" width="130">
            <template slot-scope="scope" >
                <div class="fx" style="display: flex">
                    <el-button size="mini" type="primary" @click="handleEdit(scope.row)">修改</el-button>
                    <el-button
                        icon="el-icon-delete"
                        class="el-button el-button--danger"
                        style="font-size: 15px;"
                        @click="handleDelete(scope.row,scope.$index)"
                    ></el-button>
                </div>
            </template>
      </el-table-column>
    </el-table>

    <el-dialog title="资料路径" :visible.sync="dialogFormVisible" width="80%">
        <el-table  :data="obj" stripe border fit highlight-current-row style="width: 100%;margin-top:15px;">
      <el-table-column label="培训资料1"  prop="materialForTraining1" align="center" width="200px"/>
      <el-table-column label="培训资料2"  prop="materialForTraining2" align="center" width="200px"/>
      <el-table-column label="培训资料3"  prop="materialForTraining3" align="center" width="200px"/>
      <el-table-column label="培训资料4"  prop="materialForTraining4" align="center" width="200px"/>    
      <el-table-column label="培训资料5"  prop="materialForTraining5" align="center" width="200px"/>
      <el-table-column label="考试资料1"  prop="examinationMaterials1" align="center" width="200px"/>
      <el-table-column label="考试资料2"  prop="examinationMaterials2" align="center" width="200px"/>
      <el-table-column label="考试资料3"  prop="examinationMaterials3" align="center" width="200px"/>
      <el-table-column label="考试资料4"  prop="examinationMaterials4" align="center" width="200px"/>
      <el-table-column label="考试资料5"  prop="examinationMaterials5" align="center" width="200px"/>
    </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogFormVisible = false">确 定</el-button>
      </div>
    </el-dialog>

   <!-- pagination 分页 -->
    <div class="pagination-container">
      <el-pagination
        background
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="listQuery.page"
        :page-sizes="[5,10, 20, 30, 40, 100, 300, 500]"
        :page-size="listQuery.limit"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>

    <el-divider></el-divider>

    <el-button style="margin-right: 10px" type="success" size="small" @click="hExportExcel">导出数据Excel</el-button>

  </div>
</template> 

<script>
import { getNextExecTime } from "@/api/processRoute"
import { searchWorkers } from '@/api/chargingData'
import { programFind,programSave,programUpd,programDel,tutorFind,knowledgeFind } from "@/api/knowledgeSkill"
import mixin from '../../utils/mixin.js'
import { cron } from 'vue-cron'
export default {
    name: 'trainingProgram',
    template: '<cron/>',
    components: { cron },
    mixins: [mixin],
    data () {
        return {
            listQuery: {
                page: 1,                                    //页码
                limit: 10                                   //每页多少条记录
            },
            param: {
                code: '',                      
                content: ''                    
            },
            title: '新增',
            total: 0,                                      //数据的总数
            tableInfo: [],
            tableMX:[],
            loadBool: false,
            showMX: false,
            loadingList: false,
            loading: false,
            centerList: [],                         //工作中心列表
            createForm: {},
            updForm: {},
            cronverify: false,
            cronverify1: false,
            props: { multiple: true },
            // 表单校验
            addRules: {
                workCenter: [
                    { required: true, message: "工作中心不能为空!", trigger: "change" },
                ],
                contentType: [
                    { required: true, message: "内容类别不能为空!", trigger: "change" },
                ],
                trainingContent: [
                    { required: true, message: "培训内容不能为空!", trigger: "change" },
                ],
                userName: [
                    { required: true, message: "导师/讲师不能为空!", trigger: "change" },
                ],
                trainingCategory: [
                    { required: true, message: "培训类别不能为空!", trigger: "change" },
                ],
                plannedTrainingTime: [
                    { required: true, message: "培训时间不能为空!", trigger: "change" },
                ],
                certificateType: [
                    { required: true, message: "课件类型不能为空!", trigger: "change" },
                ],
                evaluationMode: [
                    { required: true, message: "考核方式不能为空!", trigger: "change" },
                ],
                notificationTime: [
                    { required: true, message: "通知时间不能为空!", trigger: "change" },
                ],
                emailNotification: [
                    { required: true, message: "邮件通知不能为空!", trigger: "change" },
                ],
            },
            showAdd: false,
            showupd: false,
            userInfo: this.$store.state.user.userInfo,
            tutorList:[],
            typeList:['入职培训','岗前培训','岗位培训','专业培训','岗位案例培训','关键工序培训','岗位实操培训'],
            coursewareList:['系统演示','现场培训','程序文件','培训资料'],
            assessList:['现场问答','笔试','实操考核','陷阱测试'],
            contentTypeList:['生产','质量','工艺','安全','计划','商务','采购','通用','其它'],
            fileList:[], 
            fileList1:[], 
            bool1: false,
            bool2: false,
            getHttpHeader: {                    //上传文件的头
                Authorization: '',              //传输文件的token
                CHECK_USER_VALUE: 'GOLWAY',
                CHECK_PASSWORD_VALUE: '8D4DD3F80CEB6149329FDBD590B164F1'
            },
            plannedTrainingTime1:'',
            notificationTime1:'',
            MailUserName:[{name:''}],
            trainObjList:[{jobTitle:''}],
            personnelList:[],
            trainList:[],
            carbonCopyRecipientsMail:[],
            dialogFormVisible: false,
            obj:[],
            // obj:{
            //     materialForTraining1:'',
            //     materialForTraining2:'',
            //     materialForTraining3:'',
            //     materialForTraining4:'',
            //     materialForTraining5:'',
            //     examinationMaterials1:'',
            //     examinationMaterials2:'',
            //     examinationMaterials3:'',
            //     examinationMaterials4:'',
            //     examinationMaterials5:'',
            // }
        }
    },
    computed: {
      inputWid() {
        return function (value) {
            if(!value || (value.length <= 10)){
              return '150px'
            } else {
              return (150 + (String(value).length-10)*6) + 'px'
            }
        }
      }
    },
    methods: {
        // 点击培训资料
        clickFor(e){
            this.dialogFormVisible = true
            this.obj = [e]
            console.log(this.obj)
        },
        changeTutor(e){
            this.tutorList.forEach(item =>{
                if(item.id == e){
                    this.createForm.tid = item.id 
                }
            })
        },
        // 删除培训对象
        delPost(index){
        if(this.trainObjList.length == 1){
          this.trainObjList = [{jobTitle:''}]
        } else {
          this.trainObjList.splice(index, 1);
        }
      },
       async getKnowledge(){
        if(!this.trainList.length){
          const {data} = await knowledgeFind({page:1,limit:9999})
          this.trainList = data.list
        }
    },
      // 添加培训对象
      addPost(){
        this.trainObjList.push({jobTitle:''})
      },
        // 添加邮箱
      addMail(){
        if(!this.MailUserName[this.MailUserName.length -1].name){
                return this.$message.warning('请先选择人员')
            }
            this.MailUserName.push({name:''})
      },
        // 删除邮箱
      delMail(index){ 
        if(this.MailUserName.length == 1){
          this.MailUserName = [{name:''}]
        } else {
          this.MailUserName.splice(index, 1);
        }
      },
        // 岗位对象发生改变
        objChang(e,index1){
          this.trainList.forEach(item => {
            if(e){  
              if(e == item.id){
                this.trainObjList[index1].id = e
                this.trainObjList[index1].jobTitle = item.jobTitle
              }
            }

          })
      },
        // 邮箱发生改变
      mailChang(e,index1){
        this.personnelList.forEach(item => {
          if(e){
            if(e == item.userName){
                console.log(item)  
              if(item.mail && item.mail != 'null'){
                    this.MailUserName[index1].name = item.userName
                    this.MailUserName[index1].mail = item.mail
                    this.MailUserName[index1].jobNumber = item.jobNumber
              } else {
                  this.$message({
                    message: `${e}没有添加邮箱！`,
                    type: 'warning'
                  })    
                  this.MailUserName[index1].name = ''
                  this.MailUserName[index1].mail = ''
                  this.MailUserName[index1].jobNumber = ''
              }
            }
          }
        })
      },
        async businessFocus(){
            console.log(this.personnelList)
        if(!this.personnelList.length) {
          const res = await searchWorkers({page:1,limit:9999,status: 1})
          this.personnelList = res.data.records
        }
      },
        // 获取培训时间
        changeverify(val,id){
        let arr = val.split(" ");
        arr.pop()   
        if(id == 1){
            this.createForm.plannedTrainingTime=arr.join(" ")
            this.reminder5(this.createForm.plannedTrainingTime,id)
        } else if(id == 2){
            this.createForm.notificationTime=arr.join(" ")
            this.reminder5(this.createForm.notificationTime,id)
        }
      },
      // 五次提示
      async reminder5(e,id){
        let query = {
          numTimes: 5,
          cronExpression: e
        }
        const res = await getNextExecTime(query)
        if(id == 1){
            this.plannedTrainingTime1 = res.data[0]
        } else if(id == 2){
            this.notificationTime1 = res.data[0]
        }
         let messageContent = ''
        res.data.forEach(item => {  
        // 将每个项目添加到 messageContent 字符串中，并在每个项目后添加换行符  
        messageContent += `<div>${item}</div>`;  
      });
      // 去除字符串末尾的换行符（如果有的话）  
      if (messageContent.endsWith('\n')) {      
        messageContent = messageContent.slice(0, -1);  
      }  
        this.$message({     
          dangerouslyUseHTMLString: true,
          message: `<div>近五次的执行结果:</div>${messageContent}`,
          type: 'success',
          duration: 5000
        });
    },
        // 获取导师列表
        async getTutor(){
            let query = {page:1,limit:10000}
            const {data} = await tutorFind(query)
            this.tutorList = data.list
        },
        // 文件上传之前的函数，将token传入头中
        beforeFilsUpload(file) {
            this.getHttpHeader.Authorization = this.dealCookie()
        },
        // cookies的处理函数
        dealCookie() {
            const strcookie = document.cookie                     //获取cookie字符串
            const arrcookie = strcookie.split("; ")               //分割
            for ( var i = 0; i < arrcookie.length; i++) {
                const arr = arrcookie[i].split("=")
                if (arr[0] == "agent_Authorization") {
                    return arr[1]
                }
            }
            return ""
        },
        pdfRemove(e){
            if(e.status == 'fail') return this.$message.error("文件上传失败!")
            else if(e.status == 'success') return this.$message.success("文件上传成功!")
        },
        // 移除pdf
        async removePdf(file) {
            console.log(file)
          this.bool1 = false
          this.fileList = this.fileList.filter(item =>item.url != file.url)
          if(file.url == this.createForm.materialForTraining1){
            this.createForm.materialForTraining1 = null
          }else if(file.url == this.createForm.materialForTraining2){
            this.createForm.materialForTraining2 = null
          }else if(file.url == this.createForm.materialForTraining3){
            this.createForm.materialForTraining3 = null
          }else if(file.url == this.createForm.materialForTraining4){
            this.createForm.materialForTraining4 = null
          }else if(file.url == this.createForm.materialForTraining5){
            this.createForm.materialForTraining5 = null
          }
          
        },
        // 移除pdf
        async removePdf1(file) {
          this.bool2 = false    
          this.fileList1 = this.fileList1.filter(item =>item.url != file.url)
          if(file.url == this.createForm.examinationMaterials1){
            this.createForm.examinationMaterials1 = null
          }else if(file.url == this.createForm.examinationMaterials2){
            this.createForm.examinationMaterials2 = null
          }else if(file.url == this.createForm.examinationMaterials3){
            this.createForm.examinationMaterials3 = null
          }else if(file.url == this.createForm.examinationMaterials4){
            this.createForm.examinationMaterials4 = null
          }else if(file.url == this.createForm.examinationMaterials5){
            this.createForm.examinationMaterials5 = null
          }
        },
         // 上传PDF文档成功回调函数
         handlePdfSuccess(response) {
          this.bool1 = true
          if(!this.createForm.materialForTraining1){
            this.createForm.materialForTraining1 = response.results
            this.fileList.push({name: 'food.jpeg', url: response.results })
            return
          }else if(!this.createForm.materialForTraining2){
            this.createForm.materialForTraining2 = response.results
            this.fileList.push({name: 'food.jpeg', url: response.results })
            return
          }else if(!this.createForm.materialForTraining3){
            this.createForm.materialForTraining3 = response.results
            this.fileList.push({name: 'food.jpeg', url: response.results })
            return
          }else if(!this.createForm.materialForTraining4){
            this.createForm.materialForTraining4 = response.results
            this.fileList.push({name: 'food.jpeg', url: response.results })
            return
          }else if(!this.createForm.materialForTraining5){
            this.createForm.materialForTraining5 = response.results
            this.fileList.push({name: 'food.jpeg', url: response.results })
            return
          }
        },
        // 上传PDF文档成功回调函数
        handlePdfSuccess1(response) {
          this.bool1 = true
          console.log('长速',this.fileList1)
          if(!this.createForm.examinationMaterials1){
            this.createForm.examinationMaterials1 = response.results
            this.fileList1.push({name: 'food.jpeg', url: response.results })
          }else if(!this.createForm.examinationMaterials2){
            this.createForm.examinationMaterials2 = response.results
            this.fileList1.push({name: 'food.jpeg', url: response.results })
          }else if(!this.createForm.examinationMaterials3){
            this.createForm.examinationMaterials3 = response.results
            this.fileList1.push({name: 'food.jpeg', url: response.results })
          }else if(!this.createForm.examinationMaterials4){
            this.createForm.examinationMaterials4 = response.results
            this.fileList1.push({name: 'food.jpeg', url: response.results })
          }else if(!this.createForm.examinationMaterials5){
            this.createForm.examinationMaterials5 = response.results
            this.fileList1.push({name: 'food.jpeg', url: response.results })
          }
        },
        getData(){
          this.listQuery.page = 1
          this.listQuery.limit = 10
          this.handleFilter()
        },
        async handleFilter() {
            this.loadingList = true
            let query = Object.assign({},this.listQuery)
            if(this.param.workCenter){ query.workCenter = this.param.workCenter}
            if(this.param.trainingCategory){ query.trainingCategory = this.param.trainingCategory}
            if(this.param.trainingContent){ query.trainingContent = this.param.trainingContent}
            if(this.param.tid){ query.tid = this.param.tid}
            let data = await programFind(query)
            let errmsg = data.msg
            this.loadingList = false
            if(data.code == '500') return
            if(data.code != '1') return this.$message.error(errmsg)
            this.total = data.data.count
            this.tableInfo = data.data.list
        },
        // table表单下方的页码组件改变每页显示的数据条数
        handleSizeChange(val) {
          this.listQuery.limit = val
          this.handleFilter()
        },
        // table表单下方的页码组件改变页面
        handleCurrentChange(val) {
          this.listQuery.page = val
          this.handleFilter()
        },
        transformDat(res) {
          const mapInfo = {
            index: '序号',
            workCenter: '工作中心',
            contentType: '内容类别',
            trainingContent: '培训内容',
            userName: '导师/讲师',
            immediateBoss: '直接主管',
            trainingCategory: '培训类别',
            plannedTrainingTime: '计划培训时间',
            trainingObjectsStr: '培训对象(岗位)',
            evaluationMode: '考核方式',
            certificateType: '课件类型',
            emailNotification: '邮件通知',
            notificationTime: '通知时间',
            carbonCopyRecipientsUserName: '抄送人员',
            materialForTraining1: '培训资料1',
            materialForTraining2: '培训资料2',
            materialForTraining3: '培训资料3',
            materialForTraining4: '培训资料4',
            materialForTraining5: '培训资料5',  
            examinationMaterials1: '考试资料1',
            examinationMaterials2: '考试资料2',
            examinationMaterials3: '考试资料3',
            examinationMaterials4: '考试资料4',
            examinationMaterials5: '考试资料5',
            type: '状态',
            completionTime: '完成时间',
            longTrainingPeriod: '培训时长(h)',
            effectScore: '效果评分',
            evaluationQrCode: '评价二维码',
            updateJobNumber: '修改人员',
            updateTime: '修改时间',
          }
          // 对data进行格式化
          // 取出所有的属性名
          const props = Object.keys(res[0]) // ['id','']
          // 将属性名从英文转为中文
          const header = props.map(zhkey => mapInfo[zhkey])
          console.log('中文的表头', header)
          // const data=[['xxxx','总裁办'，'13800000']]
          const data = res.map(obj => Object.values(obj))
          return { header, data }
        },
        handleDelete(row,index) {
            this.$confirm('这将会永久删除该行数据，是否继续?', '警告', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.delprocess(row,index)
            }).catch(() => {
                this.$message({
                  type: 'info',
                  message: '已取消删除'
                })
            })
        },
        async delprocess(row,index){
          let res = await programDel({id: row.id})
          if(res.code == '500') return
          if(res.code != '1') return this.$message.error(res.msg)
          this.tableInfo.splice(index,1)
          this.$message.success(res.msg)
        },
        // 导出excel
        async hExportExcel() {
          this.loading = true
          let query = Object.assign({},this.listQuery)
          query.page = 1    
          query.limit = 10000
          if(this.param.workCenter){ query.workCenter = this.param.workCenter}
          if(this.param.trainingCategory){ query.trainingCategory = this.param.trainingCategory}
          if(this.param.trainingContent){ query.trainingContent = this.param.trainingContent}
          if(this.param.tid){ query.tid = this.param.tid}
          let arr = await programFind(query)
          if(arr.code == '500') return
          if(arr.code != '1'){
            this.loading = false
            return this.$message.error(errmsg)
          }
          if(!arr.data.list.length){
            this.loading = false
            this.$message.error('暂无数据')
          }
          const { header, data } = this.transformDat(this.setSort(arr.data.list))
          import('@/vendor/Export2Excel').then(excel => {
            // excel表示导入的模块对象
            console.log(excel)
            excel.export_json_to_excel({
            header, // 表头 必填
            data, // 具体数据 必填
            filename: '讲师&导师管理', // 文件名称
            autoWidth: true, // 宽度是否自适应
            bookType: 'xlsx' // 生成的文件类型
            })
          })
          this.loading = false
        },
        // 排序函数
        setSort(arr){
          let newArr = JSON.parse(JSON.stringify(arr))
          let arr1 = []
          newArr.forEach((item,index)=>{
            let obj = {
              index: index+1,
              workCenter: item.workCenter,
              contentType: item.contentType,
              trainingContent: item.trainingContent,
              userName: item.userName,
              immediateBoss: item.immediateBoss,
              trainingCategory: item.trainingCategory,
              plannedTrainingTime: item.plannedTrainingTime,
              trainingObjectsStr: item.trainingObjectsStr,
              evaluationMode: item.evaluationMode,
              certificateType: item.certificateType,
              emailNotification: item.emailNotification,
              notificationTime: item.notificationTime,
              carbonCopyRecipientsUserName: item.carbonCopyRecipientsUserName,
              materialForTraining1: item.materialForTraining1,
              materialForTraining2: item.materialForTraining2,
              materialForTraining3: item.materialForTraining3,
              materialForTraining4: item.materialForTraining4,
              materialForTraining5: item.materialForTraining5,
              examinationMaterials1: item.examinationMaterials1,
              examinationMaterials2: item.examinationMaterials2,
              examinationMaterials3: item.examinationMaterials3,
              examinationMaterials4: item.examinationMaterials4,
              examinationMaterials5: item.examinationMaterials5,
              type: item.type,
              completionTime: item.completionTime,
              longTrainingPeriod: item.longTrainingPeriod,
              effectScore: item.effectScore,
              evaluationQrCode: item.evaluationQrCode,
              updateJobNumber: item.updateJobNumber,
              updateTime: item.updateTime,
            }
            arr1.push(obj)
          })
          return arr1
        },
        cancelSubmit(){
            this.param = {    
            }
            this.listQuery.page = 1
            this.handleFilter()
        },
        // 提交表单之前先进行验证
        addfacility(formName) {
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    this.submitprocess()
                } else {
                    return false
                }
            })
        },
        closeShow(){
            if(this.title == '修改'){       
                this.createForm = {}    
                this.fileList = []
                this.fileList1 = []
                this.MailUserName = [{name:''}]
                this.trainObjList = [{jobTitle:''}]
                this.plannedTrainingTime1 = ''
                this.notificationTime1 = ''
                this.$refs.createForm.resetFields()
            }
            this.showAdd = false
        },
        async submitprocess(){
            if(!this.trainObjList[this.trainObjList.length-1].jobTitle) return this.$message.error('培训对象最后一个不能为空！')
            if(!this.MailUserName[this.MailUserName.length-1].name) return this.$message.error('邮件抄送最后一个不能为空！')
            let query = Object.assign({},this.createForm)
            let arr1 = []
            let arr2 = []
            let arr3 = []
            let arr4 = []   
            let arr5 = []   
            console.log(this.trainObjList)
            this.trainObjList.forEach(item => {
                arr4.push(item.id)
                arr5.push(item.jobTitle)
            })
            this.MailUserName.forEach(item => {
                arr1.push(item.name)
                arr2.push(item.jobNumber)
                arr3.push(item.mail)
            })
            query.carbonCopyRecipientsUserName = arr1.join(',')
            query.carbonCopyRecipientsJobNumber = arr2.join(',')
            query.carbonCopyRecipientsMail = arr3.join(',')
            query.trainingObjects = arr4.join(',')
            query.trainingObjectsStr = arr5.join(',')
            if(query.evaluationMode != '笔试'){
                query.examinationMaterials1 = null
                query.examinationMaterials2 = null
                query.examinationMaterials3 = null
                query.examinationMaterials4 = null
                query.examinationMaterials5 = null
            }
            delete query.userName
            console.log('query',query)
            console.log(this.MailUserName)
            this.loadBool = true
            let data 
            if(this.title == '新增'){
                data = await programSave(query)
            } else {
                data = await programUpd(query)
            }
            const errMsg = data.msg
            this.loadBool = false
            if(data.code == '500') return
            if(data.code != '1') return this.$message.error(errMsg)
            this.$message.success(errMsg)
            this.resetForm()
            this.showAdd = false
            this.handleFilter()
        },
        resetForm(){
            this.createForm = {}
            this.fileList = []
            this.fileList1 = []
            this.MailUserName = [{name:''}]
            this.trainObjList = [{jobTitle:''}]
            this.plannedTrainingTime1 = ''
            this.notificationTime1 = ''
            this.$refs.createForm.resetFields();
        },
        handleEdit(row){
            this.title = '修改'
            this.createForm = Object.assign({},row)
            this.createForm.userName
            console.log(this.createForm)
            let arr1 = []
            let arr2 = []
            let arr3 = []
            let arr4 = []
            let arr5 = []
            if(this.createForm.carbonCopyRecipientsUserName){ arr1 = this.createForm.carbonCopyRecipientsUserName.split(',')}
            if(this.createForm.carbonCopyRecipientsJobNumber){ arr2 = this.createForm.carbonCopyRecipientsJobNumber.split(',')}
            if(this.createForm.carbonCopyRecipientsMail){ arr3 = this.createForm.carbonCopyRecipientsMail.split(',')}
            if(this.createForm.trainingObjects){ arr5 = this.createForm.trainingObjects.split(',')}
            if(this.createForm.trainingObjectsStr){ 
                arr4 = this.createForm.trainingObjectsStr.split(',')
                this.trainObjList = arr4.map((item,index) => ({  
                  jobTitle: item,
                  id: arr5[index],
                }))
            }
            if(this.createForm.carbonCopyRecipientsUserName){
                this.MailUserName = arr1.map((item,index) => ({
                  name: item,
                  jobNumber: arr2[index],
                  mail: arr3[index],
                }))
            }
            console.log(this.trainObjList)
            this.fileList = []
            if(row.materialForTraining1){
                this.fileList.push({name: 'food.jpeg', url: row.materialForTraining1})
            }
            if(row.materialForTraining2){
                this.fileList.push({name: 'food.jpeg', url: row.materialForTraining2})
            }
            if(row.materialForTraining3){
                this.fileList.push({name: 'food.jpeg', url: row.materialForTraining3})
            }
            if(row.materialForTraining4){
                this.fileList.push({name: 'food.jpeg', url: row.materialForTraining4})
            }
            if(row.materialForTraining5){
                this.fileList.push({name: 'food.jpeg', url: row.materialForTraining5})
            }
            if(row.examinationMaterials1){
                this.fileList1.push({name: 'food.jpeg', url: row.examinationMaterials1})
            }
            if(row.examinationMaterials2){
                this.fileList1.push({name: 'food.jpeg', url: row.examinationMaterials2})
            }
            if(row.examinationMaterials3){
                this.fileList1.push({name: 'food.jpeg', url: row.examinationMaterials3})
            }
            if(row.examinationMaterials4){
                this.fileList1.push({name: 'food.jpeg', url: row.examinationMaterials4})
            }
            if(row.examinationMaterials5){
                this.fileList1.push({name: 'food.jpeg', url: row.examinationMaterials5})
            }
            this.showAdd = true
        },
        addInOrOut(){
            this.title = '新增'
            this.showAdd = true
        },
    },
    // 进入页面获取table信息
    mounted() {
        this.handleFilter()
    }
}
</script>

<style>

.btn-add{
    margin-bottom: 28px;
}

.ul-item{
  width: 85%;
}
</style>
